﻿using Pay.Core;
using Pay.Data;
using Pay.DTO;
using Pay.IService;
using Pay.Service.Cache;
using Pay.TO;
using System;
using System.Collections.Generic;
using System.Data.Entity.SqlServer;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Pay.Service {
    public class TokenUpGradeService : ServiceBase, ITokenUpGradeService, IDisposable {
        private IUnitOfWork _iUnitOfWork;
        private IMarketingCommonService _iMarketingCommonService;
        public TokenUpGradeService(IUnitOfWork iUnitOfWork, IMarketingCommonService iMarketingCommonService) : base(iUnitOfWork) {
            _iUnitOfWork = iUnitOfWork;
            _iMarketingCommonService = iMarketingCommonService;
        }

        #region 后台管理
        /// <summary>
        /// 获取升级创客记录分页列表
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public PagedResult<token_up_grade_maker_dto> GetTokenUpGradeMakerPageList(TokenUpGradeMakerQuery query) {
            var merchant = context.Merchants.Where(o => o.MerchantNo == t_RequestMethod.merchant_no).FirstOrDefault();

            var merchantFilter = PredicateBuilder.True<Merchant>();
            var q = from c in context.Charges.Where(o => o.MerchantId == merchant.Id && o.Type == 2 && (o.Status == ChargeStatus.Finish || o.Status == ChargeStatus.Processed))
                    join m in context.Merchants.Where(merchantFilter) on c.BindId equals m.Id into t1
                    from tm in t1.DefaultIfEmpty()
                    join a in context.AuthInfos.Where(o => o.Status == CertifyStatus.Auth) on tm.Id equals a.MerchantId into t2
                    from ta in t2.DefaultIfEmpty()
                    select new token_up_grade_maker_dto() {
                        charge_id = c.Id,
                        merchant_id = tm.Id,
                        mobile = tm.Mobile,
                        name = tm.Name,
                        real_name = ta.AccountName,
                        buy_price = c.PayAmount,
                        buy_time_value = c.OrderTime,
                        status = c.Status == ChargeStatus.Finish ? 1 : 2
                    };

            if (!string.IsNullOrEmpty(query.name)) {
                q = q.Where(o => o.name == query.name);
            }
            if (!string.IsNullOrEmpty(query.mobile)) {
                q = q.Where(o => o.mobile == query.mobile);
            }
            if (!string.IsNullOrEmpty(query.real_name)) {
                q = q.Where(o => o.real_name == query.real_name);
            }
            if (!string.IsNullOrEmpty(query.begin_time)) {
                long value = DateTime.Parse(query.begin_time).ToUnix();
                q = q.Where(o => o.buy_time_value >= value);
            }
            if (!string.IsNullOrEmpty(query.end_time)) {
                long value = DateTime.Parse(query.end_time).AddDays(1).ToUnix();
                q = q.Where(o => o.buy_time_value <= value);
            }

            var rowsCount = q.Count();
            var rows = q.OrderByDescending(c => c.buy_time_value).Skip((query.page - 1) * query.size).Take(query.size).ToList();
            if (rows != null && rows.Count() > 0) {
                rows.ForEach(o => { o.buy_time = o.buy_time_value.ToDateTime(); });
            }
            var result = new PagedResult<token_up_grade_maker_dto>(rows, rowsCount, query.page, query.size);

            return result;
        }

        /// <summary>
        /// 升级创客记录设为客服已处理
        /// </summary>
        /// <param name="chargeId"></param>
        /// <returns></returns>
        public bool SetTokenUpGradeMakerProcessed(long chargeId) {
            var charge = context.Charges.FindById(chargeId);
            charge.Status = ChargeStatus.Processed;
            _iUnitOfWork.Commit();
            return true;
        }


        public PagedResult<token_up_grade_dto> Gets(UpGradeQuery query) {
            var filter = PredicateBuilder.True<TokenUpGrade>();
            if (!string.IsNullOrEmpty(query.name))
                filter = filter.And(c => c.MerchantName.Contains(query.name) || c.Merchant.Mobile.Contains(query.name));
            if (query.start_time.HasValue) {
                long startTime = query.start_time.Value.ToUnix();
                filter = filter.And(c => c.ApplyTime >= startTime);
            }
            if (query.end_time.HasValue) {
                long endTime = query.end_time.Value.AddDays(1).ToUnix();
                filter = filter.And(c => c.ApplyTime <= endTime);
            }
            if (query.e_up_grade_audit.HasValue) {
                filter = filter.And(c => c.EUpGradeAudit == (EUpGradeAudit)query.e_up_grade_audit.Value);
            }
            if (query.user_id.GetValueOrDefault(0) > 0) {
                filter = filter.And(c => c.MerchantId == query.user_id.Value);
            }
            return context.TokenUpGrade.FromCachePaged<TokenUpGrade, token_up_grade_dto>(query.page, query.size, filter, orderBy => orderBy.OrderByDescending(c => c.ApplyTime));
        }
        #endregion
        /// <summary>
        /// 我的业务员开通审核分页列表
        /// </summary>
        /// <param name="query"></param>
        /// <param name="userId"></param>
        /// <returns></returns>
        public PagedResult<promoter_up_grade_audit_list_model> Gets(MarketingPromoterQuery query, long userId) {
            var filter = PredicateBuilder.True<TokenUpGrade>();
            if (!string.IsNullOrEmpty(query.promoter))
                filter = filter.And(c => c.Merchant.Mobile == query.promoter || c.ApplyMerchant.Mobile == query.promoter);
            if (query.user_type > 0) {
                filter = filter.And(c => c.GradeId == (UserType)query.user_type);
            }
            if (!string.IsNullOrEmpty(query.begin_time)) {
                long time = DateTime.Parse(query.begin_time).ToUnix();
                filter = filter.And(c => c.AuditTime >= time);
            }
            if (!string.IsNullOrEmpty(query.end_time)) {
                long time = DateTime.Parse(query.end_time).AddDays(1).ToUnix();
                filter = filter.And(c => c.AuditTime <= time);
            }

            var curMerchant = context.Merchants.FindById(userId).ToDtoObject<merchant_dto>();
            var q = from g in context.TokenUpGrade.Where(filter)
                    where ((g.ApplyMerchantId == userId) ||
                    ((curMerchant.merchant_no == t_RequestMethod.TOKEN_MARKETING_DEFAULT_MEARCHANTNO || curMerchant.usertype == UserType.tokenCityAgent) && g.CityCompanyMerchantId == userId))
                    select new promoter_up_grade_audit_list_model() {
                        id = g.Id,
                        promoter = g.ApplyMerchant.Mobile,
                        belong_to_promoter = g.Merchant.Mobile,
                        user_type = g.GradeId,
                        apply_time_value = g.ApplyTime,
                        up_grade_audit = g.EUpGradeAudit,
                        transfer_voucher = g.TransferVoucher
                    };
            var rows = q.OrderBy(o => o.up_grade_audit).ThenByDescending(c => c.apply_time_value).Skip((query.page - 1) * query.size).Take(query.size).ToList();
            if (rows != null && rows.Count() > 0)
                rows.ForEach(o => { o.apply_time = o.apply_time_value.ToDateTime(); });
            var result = new PagedResult<promoter_up_grade_audit_list_model>(rows, q.Count(), query.page, query.size);
            return result;
        }


        public token_up_grade_dto Get(long id) {
            return context.TokenUpGrade.FindById(id).ToDtoObject<token_up_grade_dto>();
        }
    }
}
